import React, { useEffect, useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  message,
  Row,
  Col,
  Statistic,
  Badge,
  Typography,
  Tooltip,
  Popconfirm,
  Steps,
  DatePicker,
  InputNumber,
} from 'antd';
import {
  CheckOutlined,
  CloseOutlined,
  TruckOutlined,
  DollarOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  SendOutlined,
  UndoOutlined,
} from '@ant-design/icons';
import type { ColumnsType, TableRowSelection } from 'antd/es/table';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;
const { Step } = Steps;

interface Order {
  id: string;
  orderNo: string;
  userName: string;
  shopName: string;
  totalAmount: number;
  finalAmount: number;
  status: 'pending' | 'paid' | 'shipped' | 'delivered' | 'cancelled' | 'refunded';
  paymentStatus: 'unpaid' | 'paid' | 'refunded';
  createdAt: string;
  items: Array<{
    productName: string;
    quantity: number;
    price: number;
  }>;
}

interface ProcessingAction {
  type: 'ship' | 'cancel' | 'refund' | 'confirm';
  orderIds: string[];
  data?: any;
}

const OrderProcessing: React.FC = () => {
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();
  
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [actionModalVisible, setActionModalVisible] = useState(false);
  const [currentAction, setCurrentAction] = useState<ProcessingAction | null>(null);

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '订单管理' },
      { title: '订单处理' },
    ]));
  }, [dispatch]);

  useEffect(() => {
    loadOrders();
  }, []);

  // 加载待处理订单
  const loadOrders = async () => {
    try {
      setLoading(true);
      // 模拟待处理订单数据
      const mockOrders: Order[] = [
        {
          id: '1',
          orderNo: 'ORD202401150001',
          userName: '张三',
          shopName: 'Apple官方旗舰店',
          totalAmount: 9999,
          finalAmount: 9999,
          status: 'paid',
          paymentStatus: 'paid',
          createdAt: '2024-01-15T10:00:00Z',
          items: [
            { productName: 'iPhone 15 Pro Max', quantity: 1, price: 9999 },
          ],
        },
        {
          id: '2',
          orderNo: 'ORD202401150002',
          userName: '李四',
          shopName: '小米官方旗舰店',
          totalAmount: 4999,
          finalAmount: 4509,
          status: 'pending',
          paymentStatus: 'unpaid',
          createdAt: '2024-01-15T11:00:00Z',
          items: [
            { productName: '小米14 Pro', quantity: 1, price: 4999 },
          ],
        },
        {
          id: '3',
          orderNo: 'ORD202401150003',
          userName: '王五',
          shopName: 'Apple官方旗舰店',
          totalAmount: 19999,
          finalAmount: 18999,
          status: 'shipped',
          paymentStatus: 'paid',
          createdAt: '2024-01-14T09:00:00Z',
          items: [
            { productName: 'MacBook Pro 16', quantity: 1, price: 19999 },
          ],
        },
      ];
      
      setOrders(mockOrders);
    } catch (error) {
      message.error('加载订单数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取状态标签
  const getStatusTag = (status: string) => {
    const statusConfig = {
      pending: { color: 'orange', text: '待付款' },
      paid: { color: 'blue', text: '已付款' },
      shipped: { color: 'cyan', text: '已发货' },
      delivered: { color: 'green', text: '已完成' },
      cancelled: { color: 'red', text: '已取消' },
      refunded: { color: 'purple', text: '已退款' },
    };
    const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  // 处理订单操作
  const handleOrderAction = (action: ProcessingAction) => {
    setCurrentAction(action);
    form.resetFields();
    setActionModalVisible(true);
  };

  // 执行订单操作
  const executeAction = async (values: any) => {
    try {
      if (!currentAction) return;
      
      const { type, orderIds } = currentAction;
      
      switch (type) {
        case 'ship':
          // await OrderService.shipOrders(orderIds, values);
          message.success(`成功发货 ${orderIds.length} 个订单`);
          break;
        case 'cancel':
          // await OrderService.cancelOrders(orderIds, values);
          message.success(`成功取消 ${orderIds.length} 个订单`);
          break;
        case 'refund':
          // await OrderService.refundOrders(orderIds, values);
          message.success(`成功退款 ${orderIds.length} 个订单`);
          break;
        case 'confirm':
          // await OrderService.confirmOrders(orderIds);
          message.success(`成功确认 ${orderIds.length} 个订单`);
          break;
      }
      
      setActionModalVisible(false);
      setSelectedRowKeys([]);
      loadOrders();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 行选择
  const rowSelection: TableRowSelection<Order> = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    getCheckboxProps: (record) => ({
      disabled: record.status === 'delivered' || record.status === 'cancelled',
    }),
  };

  // 表格列定义
  const columns: ColumnsType<Order> = [
    {
      title: '订单信息',
      key: 'orderInfo',
      width: 200,
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 500, marginBottom: 4 }}>
            {record.orderNo}
          </div>
          <div style={{ fontSize: 12, color: '#666' }}>
            {new Date(record.createdAt).toLocaleString()}
          </div>
        </div>
      ),
    },
    {
      title: '用户',
      dataIndex: 'userName',
      key: 'userName',
      width: 100,
    },
    {
      title: '商品信息',
      key: 'products',
      width: 200,
      render: (_, record) => (
        <div>
          {record.items.map((item, index) => (
            <div key={index} style={{ fontSize: 12, marginBottom: 2 }}>
              {item.productName} × {item.quantity}
            </div>
          ))}
        </div>
      ),
    },
    {
      title: '订单金额',
      key: 'amount',
      width: 120,
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 500, color: '#f50' }}>
            ¥{record.finalAmount.toFixed(2)}
          </div>
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => getStatusTag(status),
    },
    {
      title: '店铺',
      dataIndex: 'shopName',
      key: 'shopName',
      width: 120,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          {record.status === 'paid' && (
            <Tooltip title="发货">
              <Button
                type="primary"
                size="small"
                icon={<TruckOutlined />}
                onClick={() => handleOrderAction({
                  type: 'ship',
                  orderIds: [record.id],
                })}
              >
                发货
              </Button>
            </Tooltip>
          )}
          
          {(record.status === 'pending' || record.status === 'paid') && (
            <Popconfirm
              title="确定要取消这个订单吗？"
              onConfirm={() => handleOrderAction({
                type: 'cancel',
                orderIds: [record.id],
              })}
              okText="确定"
              cancelText="取消"
            >
              <Button
                size="small"
                danger
                icon={<CloseOutlined />}
              >
                取消
              </Button>
            </Popconfirm>
          )}
          
          {record.status === 'paid' && (
            <Button
              size="small"
              icon={<UndoOutlined />}
              onClick={() => handleOrderAction({
                type: 'refund',
                orderIds: [record.id],
              })}
            >
              退款
            </Button>
          )}
        </Space>
      ),
    },
  ];

  // 获取操作模态框内容
  const getModalContent = () => {
    if (!currentAction) return null;

    const { type } = currentAction;
    
    switch (type) {
      case 'ship':
        return (
          <Form form={form} layout="vertical" onFinish={executeAction}>
            <Form.Item
              label="物流公司"
              name="courier"
              rules={[{ required: true, message: '请选择物流公司' }]}
            >
              <Select placeholder="选择物流公司">
                <Option value="sf">顺丰速运</Option>
                <Option value="ems">中国邮政EMS</Option>
                <Option value="yt">圆通速递</Option>
                <Option value="zt">中通快递</Option>
                <Option value="yd">韵达速递</Option>
              </Select>
            </Form.Item>
            <Form.Item
              label="物流单号"
              name="trackingNumber"
              rules={[{ required: true, message: '请输入物流单号' }]}
            >
              <Input placeholder="请输入物流单号" />
            </Form.Item>
            <Form.Item label="备注" name="remark">
              <TextArea rows={3} placeholder="发货备注（可选）" />
            </Form.Item>
          </Form>
        );
        
      case 'cancel':
        return (
          <Form form={form} layout="vertical" onFinish={executeAction}>
            <Form.Item
              label="取消原因"
              name="reason"
              rules={[{ required: true, message: '请输入取消原因' }]}
            >
              <Select placeholder="选择取消原因">
                <Option value="out_of_stock">商品缺货</Option>
                <Option value="price_error">价格错误</Option>
                <Option value="customer_request">客户要求</Option>
                <Option value="system_error">系统错误</Option>
                <Option value="other">其他原因</Option>
              </Select>
            </Form.Item>
            <Form.Item label="详细说明" name="description">
              <TextArea rows={3} placeholder="详细说明（可选）" />
            </Form.Item>
          </Form>
        );
        
      case 'refund':
        return (
          <Form form={form} layout="vertical" onFinish={executeAction}>
            <Form.Item
              label="退款金额"
              name="refundAmount"
              rules={[{ required: true, message: '请输入退款金额' }]}
            >
              <InputNumber
                style={{ width: '100%' }}
                min={0}
                precision={2}
                placeholder="请输入退款金额"
                addonBefore="¥"
              />
            </Form.Item>
            <Form.Item
              label="退款原因"
              name="reason"
              rules={[{ required: true, message: '请选择退款原因' }]}
            >
              <Select placeholder="选择退款原因">
                <Option value="quality_issue">质量问题</Option>
                <Option value="not_as_described">与描述不符</Option>
                <Option value="customer_regret">客户后悔</Option>
                <Option value="shipping_damage">运输损坏</Option>
                <Option value="other">其他原因</Option>
              </Select>
            </Form.Item>
            <Form.Item label="退款说明" name="description">
              <TextArea rows={3} placeholder="退款说明（可选）" />
            </Form.Item>
          </Form>
        );
        
      default:
        return null;
    }
  };

  const getModalTitle = () => {
    if (!currentAction) return '';
    
    const actionNames = {
      ship: '批量发货',
      cancel: '批量取消',
      refund: '批量退款',
      confirm: '批量确认',
    };
    
    return `${actionNames[currentAction.type]} (${currentAction.orderIds.length} 个订单)`;
  };

  return (
    <div style={{ padding: '24px' }}>
      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="待付款"
              value={orders.filter(o => o.status === 'pending').length}
              valueStyle={{ color: '#faad14' }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待发货"
              value={orders.filter(o => o.status === 'paid').length}
              valueStyle={{ color: '#1890ff' }}
              prefix={<TruckOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已发货"
              value={orders.filter(o => o.status === 'shipped').length}
              valueStyle={{ color: '#52c41a' }}
              prefix={<SendOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="待处理金额"
              value={orders.filter(o => o.status === 'paid').reduce((sum, order) => sum + order.finalAmount, 0)}
              precision={2}
              prefix="¥"
              valueStyle={{ color: '#f50' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 批量操作栏 */}
      <Card style={{ marginBottom: '16px' }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Space>
              <Text>已选择 {selectedRowKeys.length} 个订单</Text>
              {selectedRowKeys.length > 0 && (
                <>
                  <Button
                    type="primary"
                    icon={<TruckOutlined />}
                    onClick={() => handleOrderAction({
                      type: 'ship',
                      orderIds: selectedRowKeys as string[],
                    })}
                  >
                    批量发货
                  </Button>
                  <Button
                    icon={<CloseOutlined />}
                    onClick={() => handleOrderAction({
                      type: 'cancel',
                      orderIds: selectedRowKeys as string[],
                    })}
                  >
                    批量取消
                  </Button>
                  <Button
                    icon={<UndoOutlined />}
                    onClick={() => handleOrderAction({
                      type: 'refund',
                      orderIds: selectedRowKeys as string[],
                    })}
                  >
                    批量退款
                  </Button>
                </>
              )}
            </Space>
          </Col>
          <Col>
            <Button icon={<ReloadOutlined />} onClick={loadOrders}>
              刷新
            </Button>
          </Col>
        </Row>
      </Card>

      {/* 订单表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          rowSelection={rowSelection}
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 操作模态框 */}
      <Modal
        title={getModalTitle()}
        open={actionModalVisible}
        onCancel={() => setActionModalVisible(false)}
        onOk={() => form.submit()}
        width={500}
        destroyOnClose
      >
        {getModalContent()}
      </Modal>
    </div>
  );
};

export default OrderProcessing;
